<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="ThreadLocal这个东西复杂吗？在我看来，对于初学者而言，还是有些难度的，其内部的存储结构挺饶的，需要沉下心来多刷刷别人的博客，然后自己根据源码、测试以及个人思考慢慢领会。 本文作为抛石引玉，给不清楚的同学给点灵感，也请大神们不吝赐教。 本系列从如下几个知识点进行分析：  ThreadLocal是什么  ThreadLocal使用场景有哪些？我喜欢通过实际的案例来引入，学有所用，这样才能学得">
<meta name="keywords" content="ThreadLocal">
<meta property="og:type" content="article">
<meta property="og:title" content="ThreadLocal自我总结（一）">
<meta property="og:url" content="http://yoursite.com/2018/04/22/thread-local-1/index.html">
<meta property="og:site_name" content="ThinkMore">
<meta property="og:description" content="ThreadLocal这个东西复杂吗？在我看来，对于初学者而言，还是有些难度的，其内部的存储结构挺饶的，需要沉下心来多刷刷别人的博客，然后自己根据源码、测试以及个人思考慢慢领会。 本文作为抛石引玉，给不清楚的同学给点灵感，也请大神们不吝赐教。 本系列从如下几个知识点进行分析：  ThreadLocal是什么  ThreadLocal使用场景有哪些？我喜欢通过实际的案例来引入，学有所用，这样才能学得">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-07-09T02:48:36.942Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ThreadLocal自我总结（一）">
<meta name="twitter:description" content="ThreadLocal这个东西复杂吗？在我看来，对于初学者而言，还是有些难度的，其内部的存储结构挺饶的，需要沉下心来多刷刷别人的博客，然后自己根据源码、测试以及个人思考慢慢领会。 本文作为抛石引玉，给不清楚的同学给点灵感，也请大神们不吝赐教。 本系列从如下几个知识点进行分析：  ThreadLocal是什么  ThreadLocal使用场景有哪些？我喜欢通过实际的案例来引入，学有所用，这样才能学得">






  <link rel="canonical" href="http://yoursite.com/2018/04/22/thread-local-1/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>ThreadLocal自我总结（一） | ThinkMore</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?13172698bcdb7ab00b7d3ec112aae9c1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ThinkMore</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">驽马十驾,功在不舍！</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archives</a>
  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/04/22/thread-local-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="文敦复">
      <meta itemprop="description" content="思考的懒惰是真的懒惰！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ThinkMore">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ThreadLocal自我总结（一）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2018-04-22 19:59:30" itemprop="dateCreated datePublished" datetime="2018-04-22T19:59:30+08:00">2018-04-22</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Modified: 2018-07-09 10:48:36" itemprop="dateModified" datetime="2018-07-09T10:48:36+08:00">2018-07-09</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/多线程/" itemprop="url" rel="index"><span itemprop="name">多线程</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><code>ThreadLocal</code>这个东西复杂吗？在我看来，对于初学者而言，还是有些难度的，其内部的存储结构挺饶的，需要沉下心来多刷刷别人的博客，然后自己根据源码、测试以及个人思考慢慢领会。</p>
<p>本文作为抛石引玉，给不清楚的同学给点灵感，也请大神们不吝赐教。</p>
<p>本系列从如下几个知识点进行分析：</p>
<ul>
<li><p><code>ThreadLocal</code>是什么</p>
</li>
<li><p><code>ThreadLocal</code>使用场景有哪些？我喜欢通过实际的案例来引入，学有所用，这样才能学得快。</p>
</li>
</ul>
<blockquote>
<p>备注：知识这种东西，对于普通人来说，第一次接触很多东西都不好消化，但是如果你有恒心和毅力，多看看、多想想，困难的事情就会慢慢变得简单。</p>
</blockquote>
<a id="more"></a>
<h1 id="ThreadLocal-是什么"><a href="#ThreadLocal-是什么" class="headerlink" title="ThreadLocal 是什么"></a>ThreadLocal 是什么</h1><p><code>ThreadLocal</code>类用来提供线程内部的局部变量。</p>
<p>这些变量在多线程环境下访问(通过get或set方法访问)时能保证各个线程里的变量相对独立于其他线程内的变量，ThreadLocal实例通常来说都是private static类型。  </p>
<p>所以说：ThreadLocal不是为了解决多线程访问共享变量，而是为每个线程创建一个单独的变量副本，提供了保持对象的方法和避免参数传递的复杂性。</p>
<h1 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h1><p><code>ThreadLocal</code>的主要应用场景为按线程多实例（每个线程对应一个实例）的对象的访问，并且这个对象很多地方都要用到。</p>
<p>例如：同一个网站登录用户，每个用户服务器会为其开一个线程，每个线程中创建一个<code>ThreadLocal</code>，里面存用户基本信息等，在很多页面跳转时，会显示用户信息或者得到用户的一些信息等频繁操作，这样多线程之间并没有联系而且当前线程也可以及时获取想要的数据。</p>
<p>比如下面的实际应用场景：在一个管理系统中，需要在 <code>Service</code> 层记录当前进行操作的用户的 <strong>唯一标识</strong>。这个唯一标识从根本来看是保存在浏览器的 <code>cookie</code> 中的，我在 <code>Controller</code> 层不管通过 <code>HttpServletRequest</code>还是其他手段（这里展开讲，又可以写个博文了，所以就此打住）都可以获取到这个唯一标识。</p>
<p>如果<code>Service</code> 层进行操作的时候，也需要这个唯一标识，其中一个不优雅但是很实用的办法就是，<code>Service</code> 层每一个方法都有一个形参来让 <code>Controller</code> 层调用 <code>Service</code> 层的时候，将这个唯一的标识传递过去，代码如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Controller 层代码</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Result <span class="title">modifyPerson</span><span class="params">(Person person,String userId)</span></span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Service 层的代码</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">modifyPerson</span><span class="params">(Person person,String userId)</span></span>&#123;&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">deletePerson</span><span class="params">(Person person,String userId)</span></span>&#123;&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;Person&gt; <span class="title">findPerson</span><span class="params">(Person person,String userId)</span></span>&#123;&#125;</span><br></pre></td></tr></table></figure>
<p>在上述<code>Service</code>层代码中，其实 <code>userId</code> 的作用仅仅是在输出 <code>log</code> 日志的时候，将当前操作的用户打印出来和实际的业务是没有任何关系的。</p>
<p>大家觉得这样的设计是不是很坑爹 ▄█▀█●</p>
<p>那么有没有办法，不显式的传递<code>userId</code>但是却可以从某个地方获取到这个<code>userId</code>了？</p>
<p>答案肯定是有的，可以利用<code>ThreadLocal</code> 从字面意思来理解这就是一个线程本地变量，可以简单理解为 将变量存储到当前线程中。那么只要还在这个线程中，肯定有办法获取到这个变量。</p>
<p>那么如何使用了？</p>
<h1 id="如何使用"><a href="#如何使用" class="headerlink" title="如何使用"></a>如何使用</h1><h2 id="举例一"><a href="#举例一" class="headerlink" title="举例一"></a>举例一</h2><p>我给出一个参考做法，直接上代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MicLocalContext</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 局部变量</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;CmdBO&gt; CMD_BO_THREAD_LOCAL = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 设置全局变量</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> cmdBO 关键信息</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setLocalContext</span><span class="params">(CmdBO cmdBO)</span> </span>&#123;</span><br><span class="line">        CMD_BO_THREAD_LOCAL.set(cmdBO);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取全局的 CmdBo 变量</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> CmdBo 变量</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> CmdBO <span class="title">getLocalContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> CMD_BO_THREAD_LOCAL.get();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 重置 CmdBo 变量&lt;br&gt;</span></span><br><span class="line"><span class="comment">     * &lt;Strong&gt;一定要记得调用&lt;/Strong&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">restLocalContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CMD_BO_THREAD_LOCAL.remove();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述代码还是比较简单的：</p>
<ul>
<li>首先定义一个入口类<code>MicLocalContext</code>,在其中定义一个<code>private static final</code> 的变量。</li>
<li>然后定义公共的<code>get</code>、<code>set</code>、<code>clear</code>的等方法来进行对应<code>ThreadLocal</code>的操作。</li>
</ul>
<p>定义好后，可以在业务的某个开头的部分，将需要在本次线程共享的变量放入<code>ThreadLocal</code>中。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">MicLocalContext.setLocalContext(cmdBO);</span><br></pre></td></tr></table></figure>
<p>当需要在这个线程中使用的时候，可以通过：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CmdBO bo = MicLocalContext.getLocalContext();</span><br></pre></td></tr></table></figure>
<p>基本的用法就这个简单，不过请一定记住，在业务的最后调用 <code>restLocalContext()</code>清空这个变量，这样可以有效的防止内存泄露。</p>
<h2 id="举例二"><a href="#举例二" class="headerlink" title="举例二"></a>举例二</h2><h3 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h3><p>这里补充句，其实 <code>ThreadLocal</code>在 SpringMVC 中有使用到，很多时候我们没有感知到而已，比如说：我们需要在 <code>Service</code> 层获取 <code>HttpServeletRequest</code> 我们可以采取如下办法：</p>
<p>先在 <code>web.xml</code>定义一个 <code>listner</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">listener-class</span>&gt;</span>org.springframework.web.context.request.RequestContextListener<span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>然后在项目中就可以通过如下代码进行使用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();</span><br></pre></td></tr></table></figure>
<p>我们来分析下这个底层的实现，通过这些实现，我们来分析我们需要注意什么！</p>
<h3 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RequestContextListener</span> <span class="keyword">implements</span> <span class="title">ServletRequestListener</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requestInitialized</span><span class="params">(ServletRequestEvent requestEvent)</span> </span>&#123;</span><br><span class="line">	   <span class="comment">// 省略....</span></span><br><span class="line">		LocaleContextHolder.setLocale(request.getLocale());</span><br><span class="line">		RequestContextHolder.setRequestAttributes(attributes);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requestDestroyed</span><span class="params">(ServletRequestEvent requestEvent)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 省略....</span></span><br><span class="line">		<span class="keyword">if</span> (threadAttributes != <span class="keyword">null</span>) &#123;</span><br><span class="line">			LocaleContextHolder.resetLocaleContext();</span><br><span class="line">			RequestContextHolder.resetRequestAttributes();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 省略....</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>首先该类实现了一个接口<code>ServletRequestListener</code> 从名字可以猜出是监听 <code>Servlet</code> 初始化，从其要求实现的方法来看，确实如此。</li>
<li>在<code>requestInitialized</code> 中，通过<code>LocaleContextHolder</code>和<code>RequestContextHolder</code>设置了当前线程共享的变量。</li>
<li>在<code>requestDestroyed</code> 中通过<code>resetLocaleContext</code> 进行了 clear.【这里请思考为什么要 clear,不 clear 有问题吗？】</li>
</ul>
<p>那么我们继续看一个 <code>LocaleContextHolder</code>的实现，对比上面的<code>MicLocalContext</code>是不是很眼熟了！</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">LocaleContextHolder</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;LocaleContext&gt; localeContextHolder = <span class="keyword">new</span> NamedThreadLocal(<span class="string">"LocaleContext"</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;LocaleContext&gt; inheritableLocaleContextHolder = <span class="keyword">new</span> NamedInheritableThreadLocal(<span class="string">"LocaleContext"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LocaleContextHolder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">resetLocaleContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        localeContextHolder.remove();</span><br><span class="line">        inheritableLocaleContextHolder.remove();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setLocaleContext</span><span class="params">(LocaleContext localeContext)</span> </span>&#123;</span><br><span class="line">        setLocaleContext(localeContext, <span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> LocaleContext <span class="title">getLocaleContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> localeContext;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>其实这种用法在 springmvc 中非常常见，如果你乐于发现，乐于思考，会看到类似代码在很多地方有使用。</p>
</blockquote>
<h1 id="使用总结"><a href="#使用总结" class="headerlink" title="使用总结"></a>使用总结</h1><ol>
<li>定义一个<code>XxxHolder</code> 来作为一个容器，存放 <code>ThreadLocal</code></li>
<li>定义一个<code>private static final ThreadLocal&lt;T&gt;</code> 用来存放<code>ThreadLocal</code></li>
<li>定义3个方法：get set remove </li>
</ol>
<p>就这么简单~~~</p>
<blockquote>
<p>您有任何建议和意见，请Email联系: <a href="mailto:hicode_club@163.com" target="_blank" rel="noopener">hicode_club@163.com</a></p>
<p>转载请保留出处 <a href="http://www.hicode.club" target="_blank" rel="noopener">HiCode 俱乐部</a></p>
</blockquote>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/04/19/think-nio-mine/" rel="next" title="NIO-概念理解">
                <i class="fa fa-chevron-left"></i> NIO-概念理解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/24/thread-local-2/" rel="prev" title="ThreadLocal自我总结（二）">
                ThreadLocal自我总结（二） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">文敦复</p>
              <p class="site-description motion-element" itemprop="description">思考的懒惰是真的懒惰！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">37</span>
                    <span class="site-state-item-name">categories</span>
                  
                </div>
              

              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#ThreadLocal-是什么"><span class="nav-number">1.</span> <span class="nav-text">ThreadLocal 是什么</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用场景"><span class="nav-number">2.</span> <span class="nav-text">使用场景</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#如何使用"><span class="nav-number">3.</span> <span class="nav-text">如何使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#举例一"><span class="nav-number">3.1.</span> <span class="nav-text">举例一</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#举例二"><span class="nav-number">3.2.</span> <span class="nav-text">举例二</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基本使用"><span class="nav-number">3.2.1.</span> <span class="nav-text">基本使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#源码分析"><span class="nav-number">3.2.2.</span> <span class="nav-text">源码分析</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用总结"><span class="nav-number">4.</span> <span class="nav-text">使用总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文敦复</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme – <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Muse</a> v6.4.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.0"></script>



  



  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
